<script setup>
import { ref, reactive, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Edit,
  View,
  Delete,
  List,
  WarningFilled,
} from "@element-plus/icons-vue";

import {
  getHouseAreas,
  addHouseArea,
  updateHouseArea,
  deleteHouseArea,
} from "../../../api/house.js";

const props = defineProps({
  houseId: {
    type: [Number, null],
    required: true,
  },
  show: {
    type: Boolean,
    default: false,
  },
  // 抽屉类型 ('add', 'edit', 'view')
  parentType: {
    type: String,
    default: "view",
  },
});

const loading = ref(false);
const areaList = ref([]);
const total = ref(0);

// 查询参数 (区域列表分页和筛选)
const queryParams = ref({
  page: 1,
  pageSize: 10,
  areaName: "",
  status: "",
});

// 筛选状态下拉框选项
const filterStatusOptions = ref([
  { value: "", label: "全部" },
  { value: 1, label: "可用" },
  { value: 2, label: "占用" },
  { value: 0, label: "停用" },
  { value: -1, label: "弃用" },
]);

// 区域类型选项
const areaStorageTypeOptions = ref([
  { value: 1, label: "常温区" },
  { value: 2, label: "冷藏区" },
  { value: 3, label: "冷冻区" },
  { value: 4, label: "其他区" },
]);

// 仓库区域状态选项
const areaStatusOptions = ref({
  1: { label: "可用", type: "success" }, // 绿色
  2: { label: "占用", type: "warning" }, // 黄色
  0: { label: "停用", type: "danger" }, // 红色
  "-1": { label: "弃用", type: "info" }, // 灰色
});

// 模态框中可编辑/新增时选择的状态选项
const areaEditableStatusOptions = ref([
  { value: 1, label: "可用" },
  { value: 2, label: "占用" },
  { value: 0, label: "停用" },
]);

// 获取区域状态信息
const getStatusInfo = (status) => {
  const key = String(status);
  return areaStatusOptions.value[key] || { label: "未知", type: "info" };
};

// 区域表单及弹窗
const defaultAreaFormData = {
  area_id: null,
  code: "",
  area_name: "",
  storage_type: 1,
  condition: "",
  notes: "",
  status: 1,
};

const areaFormData = reactive({ ...defaultAreaFormData });
const areaFormRef = ref(null);

// 原始数据
const originalAreaFormData = ref(null);

const areaDialog = reactive({
  visible: false,
  title: "",
  type: "add",
  id: null,
});

// 区域表单校验规则
const areaRules = reactive({
  area_name: [
    { required: true, message: "区域名称不能为空", trigger: "blur" },
    { max: 50, message: "区域名称不能超过 50 个字符", trigger: "blur" },
  ],
  storage_type: [
    { required: true, message: "请选择存储类型", trigger: "change" },
  ],
  condition: [
    { max: 100, message: "存储条件不能超过 100 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择区域状态", trigger: "change" }],
});

// 阻止默认右键浏览器菜单
const handleRowContextMenu = (row, column, event) => {
  if (event && event.preventDefault) {
    event.preventDefault();
  }
};

// 加载区域列表
async function loadAreaList(houseId) {
  if (!houseId || !props.show) {
    areaList.value = [];
    total.value = 0;
    return;
  }

  loading.value = true;
  try {
    const params = {
      status: queryParams.value.status,
    };

    const res = await getHouseAreas(houseId, params);

    if (res.code === 0 && res.data) {
      areaList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "获取仓库区域列表失败");
      areaList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("加载区域列表失败:", error);
    ElMessage.error("加载区域列表失败，请检查网络服务");
  } finally {
    loading.value = false;
  }
}

// 监听 houseId 、 show 属性的变化 重新加载数据
watch(
  () => [props.houseId, props.show],
  ([newId, newShow]) => {
    if (newId && newShow) {
      queryParams.value.status = null;
      loadAreaList(newId, true);
    } else if (!newShow) {
      areaList.value = [];
      total.value = 0;
    }
  },
  { immediate: true }
);

// 监听筛选
watch(
  () => queryParams.value.status,
  () => {
    if (props.houseId && props.show) {
      loadAreaList(props.houseId, true);
    }
  }
);

// 获取区域类型名称
const getStorageTypeName = (type) => {
  const option = areaStorageTypeOptions.value.find((o) => o.value === type);
  return option ? option.label : "未知";
};

// 检查表单数据是否被修改
const isAreaFormModified = () => {
  if (!originalAreaFormData.value) return false;

  const currentData = JSON.parse(
    JSON.stringify({
      area_name: areaFormData.area_name,
      storage_type: areaFormData.storage_type,
      condition: areaFormData.condition,
      notes: areaFormData.notes,
      status: areaFormData.status,
    })
  );

  const originalData = JSON.parse(
    JSON.stringify({
      area_name: originalAreaFormData.value.area_name,
      storage_type: Number(originalAreaFormData.value.storage_type),
      condition: originalAreaFormData.value.condition,
      notes: originalAreaFormData.value.notes,
      status: Number(originalAreaFormData.value.status),
    })
  );

  return JSON.stringify(currentData) !== JSON.stringify(originalData);
};

const openAreaDialog = (type, row = null) => {
  areaDialog.type = type;
  areaDialog.id = row ? row.area_id : null;

  if (type === "add") {
    Object.assign(areaFormData, defaultAreaFormData);
    areaFormData.code = "保存后自动生成";
    originalAreaFormData.value = JSON.parse(
      JSON.stringify(defaultAreaFormData)
    );
  } else if (row) {
    const dataToAssign = {
      ...row,
      storage_type: Number(row.storage_type),
      status: Number(row.status),
      condition: row.condition,
    };
    Object.assign(areaFormData, dataToAssign);

    originalAreaFormData.value = JSON.parse(JSON.stringify(dataToAssign));
  }

  areaDialog.title =
    type === "add"
      ? "新增仓库区域"
      : type === "edit"
      ? "编辑仓库区域"
      : "查看仓库区域";
  areaDialog.visible = true;

  nextTick(() => {
    areaFormRef.value?.clearValidate();
  });
};

// 区域表单保存
const handleSaveArea = async () => {
  // 校验表单
  const valid = await areaFormRef.value.validate();
  if (!valid) {
    ElMessage.error("请检查区域表单输入是否正确");
    return;
  }

  ElMessageBox.confirm(
    `确认要${areaDialog.type === "add" ? "新增" : "更新"}区域【${
      areaFormData.area_name
    }】吗?`,
    "操作确认",
    { confirmButtonText: "确定保存", cancelButtonText: "取消", type: "info" }
  )
    .then(async () => {
      await executeSubmitArea();
    })
    .catch(() => {
      ElMessage.info("已取消保存");
    });
};

// 提交表单
const executeSubmitArea = async () => {
  let apiCall;
  let successMsg = "";
  const data = {
    area_name: areaFormData.area_name,
    storage_type: areaFormData.storage_type,
    condition: areaFormData.condition,
    notes: areaFormData.notes,
    status: areaFormData.status,
  };

  if (areaDialog.type === "add") {
    apiCall = addHouseArea(props.houseId, data);
    successMsg = "新增区域成功！";
  } else if (areaDialog.type === "edit") {
    apiCall = updateHouseArea(areaDialog.id, data);
    successMsg = "编辑区域成功！";
  }

  try {
    const res = await apiCall;
    if (res.code === 0) {
      ElMessage.success(res.msg || successMsg);
      areaDialog.visible = false;
      // 保存成功后，清除原始数据快照
      originalAreaFormData.value = null;
      loadAreaList(props.houseId);
    } else {
      ElMessage.error(res.msg || "区域操作失败");
    }
  } catch (error) {
    console.error("区域提交失败:", error);
    ElMessage.error(error.message || "区域提交失败，请检查网络或后端服务");
  }
};

// 停用仓库区域
const handleDisableArea = (row) => {
  ElMessageBox.confirm(
    `此操作将**停用**区域【${row.area_name}】，是否继续?`,
    "警告",
    {
      confirmButtonText: "确定停用",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(async () => {
      try {
        const res = await deleteHouseArea(row.area_id);
        if (res.code === 0) {
          ElMessage.success(res.msg || "区域已成功停用！");
          loadAreaList(props.houseId);
        } else {
          ElMessage.error(res.msg || "区域停用失败");
        }
      } catch (error) {
        console.error("停用区域失败:", error);
        ElMessage.error("停用区域失败，请检查网络或后端服务");
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 删除仓库区域
const handlePermanentDeleteArea = (row) => {
  ElMessageBox.confirm(
    `此操作将**删除**区域【${row.area_name}】，是否继续?`,
    "严重警告",
    {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "error",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(async () => {
      try {
        const updateData = {
          area_name: row.area_name,
          storage_type: Number(row.storage_type),
          condition: row.condition,
          notes: row.notes,
          status: -1,
        };

        const res = await updateHouseArea(row.area_id, updateData);

        if (res.code === 0) {
          ElMessage.success(res.msg || "区域已成功删除！");
          loadAreaList(props.houseId);
        } else {
          ElMessage.error(res.msg || "区域删除失败");
        }
      } catch (error) {
        console.error("删除区域失败:", error);
        ElMessage.error("删除区域失败，请检查网络或后端服务");
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 检查数据是否修改
const handleDialogClose = (done) => {
  if (areaDialog.type !== "view" && isAreaFormModified()) {
    ElMessageBox.confirm("您确定要关闭吗? 未保存的修改将会丢失。", "操作确认", {
      confirmButtonText: "确定关闭",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        originalAreaFormData.value = null;
        done();
      })
      .catch(() => {});
  } else {
    originalAreaFormData.value = null;
    done();
  }
};

const handleAreaCancel = () => {
  const done = () => {
    areaDialog.visible = false;
  };
  handleDialogClose(done);
};
</script>
<template>
  <div v-if="props.show" class="house-area-list-container">
    <h4 class="form-section-title section-padding-bottom">
      <div class="title-left">
        <el-icon><List /></el-icon>
        <span>仓库区域列表 ({{ total }})</span>
      </div>

      <div class="title-middle">
        <el-select
          v-model="queryParams.status"
          placeholder="全部"
          size="default"
          style="width: 100px; margin-right: 15px"
          clearable
        >
          <el-option
            v-for="item in filterStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>

      <el-button
        v-if="houseId && props.show && parentType !== 'view'"
        type="primary"
        :icon="Plus"
        size="default"
        class="header-action-button"
        @click="openAreaDialog('add')"
      >
        新增仓库区域
      </el-button>
    </h4>
    <el-alert
      v-if="!houseId"
      title="请先保存仓库信息以添加/查看区域"
      type="warning"
      :icon="WarningFilled"
      show-icon
      :closable="false"
      style="margin-bottom: 15px"
    />
    <el-table
      :data="areaList"
      style="width: 100%"
      v-loading="loading"
      header-cell-class-name="table-header-cell"
      size="small"
      max-height="300"
      :row-key="(row) => row.area_id"
      @row-contextmenu="handleRowContextMenu"
    >
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column
        prop="code"
        label="区域编号"
        width="120"
        align="center"
      />
      <el-table-column
        prop="area_name"
        label="区域名称"
        min-width="80"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="storage_type"
        label="区域类型"
        width="80"
        align="center"
      >
        <template #default="scope">
          {{ getStorageTypeName(scope.row.storage_type) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="condition"
        label="存储条件"
        min-width="120"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ scope.row.condition || "无要求" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态/操作"
        width="180"
        align="center"
        class-name="area-status-actions-column"
      >
        <template #default="scope">
          <el-tag
            class="area-status-tag"
            :type="getStatusInfo(scope.row.status).type"
            disable-transitions
            size="small"
            >{{ getStatusInfo(scope.row.status).label }}
          </el-tag>
          <div class="area-actions-row area-actions-hidden">
            <el-button
              link
              type="info"
              :icon="View"
              size="small"
              @click="openAreaDialog('view', scope.row)"
              >查看</el-button
            >
            <template v-if="parentType !== 'view'">
              <el-button
                link
                type="primary"
                :icon="Edit"
                size="small"
                :disabled="scope.row.status === -1"
                @click="openAreaDialog('edit', scope.row)"
                >编辑</el-button
              >

              <el-button
                v-if="scope.row.status === 1 || scope.row.status === 2"
                link
                type="danger"
                :icon="Delete"
                size="small"
                @click="handleDisableArea(scope.row)"
                >停用</el-button
              >

              <el-button
                v-if="scope.row.status === 0"
                link
                type="danger"
                :icon="Delete"
                size="small"
                @click="handlePermanentDeleteArea(scope.row)"
                >删除</el-button
              >
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="areaDialog.visible"
      :title="areaDialog.title"
      width="600"
      :close-on-click-modal="true"
      :before-close="handleDialogClose"
    >
      <el-form
        :model="areaFormData"
        :rules="areaRules"
        ref="areaFormRef"
        label-width="80px"
        label-position="right"
        :disabled="areaDialog.type === 'view'"
      >
        <h4 class="form-section-title section-padding-bottom">基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域编号" prop="code">
              <el-input
                v-model="areaFormData.code"
                disabled
                placeholder="保存后自动生成"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="area_name" required>
              <el-input
                v-model="areaFormData.area_name"
                placeholder="请输入区域名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存储类型" prop="storage_type" required>
              <el-select
                v-model="areaFormData.storage_type"
                placeholder="请选择类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in areaStorageTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" required>
              <el-select
                v-model="areaFormData.status"
                placeholder="请选择区域状态"
                style="width: 100%"
                :disabled="areaDialog.type === 'view'"
              >
                <el-option
                  v-for="item in areaEditableStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="存储条件" prop="condition">
              <el-input
                v-model="areaFormData.condition"
                placeholder="例如: 温度 2-8°C, 湿度 RH 40-60%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <h4 class="form-section-title section-padding-bottom">其他</h4>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input
                v-model="areaFormData.notes"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAreaCancel">取消</el-button>
          <el-button
            v-if="areaDialog.type !== 'view'"
            type="primary"
            @click="handleSaveArea"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="less">
.house-area-list-container {
  // margin-top: 20px;
  padding-top: 10px;
}

.form-section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid rgb(217, 217, 217);

  .el-icon {
    margin-right: 5px;
    color: #1b82f1;
  }
}

.form-section-title {
  .title-left {
    display: flex;
    align-items: center;
    span {
      margin-right: 15px;
    }
  }

  .title-middle {
    flex-grow: 1;
    display: flex;
    justify-content: flex-start;
  }

  .header-action-button {
    flex-shrink: 0;
  }
}

:deep(.el-table) {
  --el-table-header-bg-color: #f7f7f7;
  --el-table-header-text-color: #262626;
  --el-table-row-hover-bg-color: #f0f0f0;
}

.area-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;

  :deep(.el-pagination) {
    .el-pagination__sizes,
    .el-pagination__jump {
      margin-left: 5px;
    }
    .el-pager li,
    .btn-prev,
    .btn-next {
      min-width: 24px;
      height: 24px;
      line-height: 24px;
      font-size: 12px;
      padding: 0 5px;
    }
  }
}

:deep(.el-table__body tr) {
  height: 40px;
}
:deep(.el-table__body .el-table__cell) {
  padding: 4px 0;
}

:deep(.area-status-actions-column) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
}

.area-actions-row {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 24px;
}

.area-actions-hidden {
  display: none !important;
}
.area-status-tag {
  display: inline-block !important;
  line-height: 20px;
}

:deep(.el-table__row:hover) {
  .area-status-actions-column {
    .area-actions-hidden {
      display: flex !important;
    }
    .area-status-tag {
      display: none !important;
    }
  }
}

:deep(.el-dialog__header) {
  padding-bottom: 18px;
  margin-bottom: 10px;
  border-bottom: 1px solid rgb(217, 217, 217);
}

:deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 20px;
  color: #262626;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 0 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

.form-section-title {
  margin-top: 0px;
  margin-bottom: 18px;
  padding-bottom: 8px;
}
</style>
